﻿#region

using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar;

#endregion

namespace Vin.Extension.SqlSugar.ActionFilter;

/// <summary>
/// 方法仅适用于控制器Action的过滤器
/// </summary>
public class VinRepositoryTransaction(ISqlSugarClient client) : Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 开启事务
        await client.AsTenant().BeginTranAsync();
        // 执行下一个过滤器以及Action
        var resultContext = await next();
        // 判断是否有异常
        if (resultContext.Exception == null)
            await client.AsTenant().CommitTranAsync();
        else
            await client.AsTenant().RollbackTranAsync();
    }
}